package collision;

import data.InstrumentGraphics;
import instruments.Instrument;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;

/**
 * @author sad
 */
public class JDrawField extends JPanel {
    private Instrument currentInstrument;

    public JDrawField() {
        init();
    }

    public void setInstrument(Instrument instrument) {
        if (currentInstrument != null) {
            currentInstrument.closeInstrument();
        }

        currentInstrument = instrument;
        currentInstrument.initInstrument();
        redraw();
    }

    public void resetInsrument() {
        if (currentInstrument != null) {
            currentInstrument.closeInstrument();
            currentInstrument = null;
        }

        redraw();
    }

    private void init() {
        addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (currentInstrument != null) {
                    currentInstrument.mouseClick(e.getX(), e.getY(), e.getModifiersEx());
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
                if (currentInstrument != null) {
                    currentInstrument.mouseDown(e.getX(), e.getY(), e.getModifiersEx());
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (currentInstrument != null) {
                    currentInstrument.mouseUp(e.getX(), e.getY(), e.getModifiersEx());
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
        addMouseMotionListener(new MouseMotionListener() {
            @Override
            public void mouseDragged(MouseEvent e) {
                if (currentInstrument != null) {
                    currentInstrument.mouseMove(e.getX(), e.getY(), e.getX(), e.getY());
                }
            }

            @Override
            public void mouseMoved(MouseEvent e) {
                if (currentInstrument != null) {
                    currentInstrument.mouseMove(e.getX(), e.getY(), e.getX(), e.getY());
                }
            }
        });
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (currentInstrument != null) {
            InstrumentGraphics graph=new InstrumentGraphics(g);
            currentInstrument.onDraw(graph);
        }
    }

    public void redraw() {
        invalidate();
        repaint();
    }
}
